package com.xiebishe.mylibrary.base;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;

import com.google.android.gms.common.util.CollectionUtils;
import com.trello.rxlifecycle3.components.support.RxFragment;
import com.xiebishe.mylibrary.common.mvp.IPresenter;
import com.xiebishe.mylibrary.common.mvp.IView;
import com.xiebishe.mylibrary.common.pageStatus.DefaultStatusHandler;
import com.xiebishe.mylibrary.common.pageStatus.OnStatusChangeListener;
import com.xiebishe.mylibrary.common.pageStatus.StatusHandler;


import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import kotlin.coroutines.CoroutineContext;
import kotlinx.coroutines.CoroutineScope;
import kotlinx.coroutines.Dispatchers;
import kotlinx.coroutines.Job;
import kotlinx.coroutines.SupervisorKt;


/**
 * @class BaseFragment
 * @describe Fragment的基类
 * <p>
 * 1.包括显示不同状态的界面
 * 2.ButterKnife的绑定和解绑
 * 3.EventBus的注册和注销
 */
public abstract class BaseFragment extends RxFragment implements IView, CoroutineScope {

    protected Context mContext;
    protected FragmentActivity mActivity;
    private boolean isShowInPager = true;
    private List<OnStatusChangeListener> temp;
    private Set<IPresenter> mPresenters;
    protected StatusHandler statusHandler;
    private Job job;
    private CoroutineContext coroutineContext;

    public BaseFragment() {

    }

    @NotNull
    @Override
    public CoroutineContext getCoroutineContext() {
        return coroutineContext;
    }

    @Override
    public void onAttach(@NotNull Context context) {
        mActivity = (FragmentActivity) context;
        mContext = context;
        super.onAttach(context);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        job = SupervisorKt.SupervisorJob(null);
        coroutineContext = Dispatchers.getMain().plus(job);
        mPresenters = new HashSet<>();
        // && !EventBus.getDefault().isRegistered(this)
        if (useEventBus())
            EventBus.getDefault().register(this);



    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View result = null;
        if (getLayoutView() != null) {
            result = getLayoutView();
        } else if (getLayoutId() != 0) {
            result = inflater.inflate(getLayoutId(), container,false);
        }
        if (result instanceof ViewGroup && DefaultStatusHandler.isCompleteSuppert((ViewGroup) result)) {
            statusHandler = createStatusHandler((ViewGroup) result);
            addTempStatusListener();
        } else if (result != null) {
            FrameLayout frameLayout = new FrameLayout(inflater.getContext());
            frameLayout.addView(result, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            result = frameLayout;
            statusHandler = createStatusHandler((ViewGroup) result);
            addTempStatusListener();
        }

        return result;
    }

    private void addTempStatusListener() {
        if (temp != null && !temp.isEmpty()) {
            for (OnStatusChangeListener onStatusChangeListener : temp) {
                statusHandler.addOnStatusChangeListener(onStatusChangeListener);
            }
        }
    }

    public void addOnStatusChangeListener(OnStatusChangeListener l) {
        if (statusHandler != null) {
            statusHandler.addOnStatusChangeListener(l);
        } else {
            if (temp == null) temp = new ArrayList<>();
            temp.add(l);
        }
    }


    protected @NotNull StatusHandler createStatusHandler(@NotNull ViewGroup result) {
        return new DefaultStatusHandler(result, v -> reloadData());
    }


    protected void reloadData() {
        loadData(null);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        loadData(savedInstanceState);
        doCustomThingsBetweenDataAndView(view);
        initViews(view, savedInstanceState);
        doCustomThingsAfterView(view);
    }


    public final boolean isTotalHidden() {
        boolean hidden = isHidden();
        if (hidden) return true;
        BaseFragment parentFragment = (BaseFragment) getParentFragment();
        while (parentFragment != null) {
            hidden = parentFragment.isHidden();
            if (hidden) return true;
            parentFragment = (BaseFragment) parentFragment.getParentFragment();
        }
        return false;
    }

    protected void pageShow() {
    }

    protected void pageShowEmpty() {
    }

    protected void pageShowError() {
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (!CollectionUtils.isEmpty(mPresenters)) {
            for (IPresenter presenter : mPresenters) {
                presenter.onDestroy();
            }
            mPresenters.clear();
        }
        job.cancel(null);
        if (EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().unregister(this);//解除注册eventbus
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }


    public View getLayoutView() {
        return null;
    }


    /**
     * 增加presenter进容器
     *
     * @param presenter
     */
    @Override
    public IPresenter addPresenter(IPresenter presenter) {
        mPresenters.add(presenter);
        return presenter;
    }

    /*
     * --------------------------------------子类  必须   实现的部分，包括:获得contentView的id,初始化view-----------------------
     */

    protected abstract int getLayoutId();

    protected abstract void initViews(View rootView, @Nullable Bundle savedInstanceState);

    protected abstract void loadData(@Nullable Bundle savedInstanceState);


    /*
     * --------------------------------------子类  选择   实现的部分，包括:是否需要EventBus-----------------------
     */

    /**
     * 是否使用eventBus,默认为不使用(false)，
     *
     * @return 返回true为需要使用
     */
    public boolean useEventBus() {
        return false;
    }

    protected void doCustomThingsBetweenDataAndView(View rootView) {
    }

    protected void doCustomThingsAfterView(View rootView) {
    }


    /**
     * --------------------------------------默认实现IView的接口-----------------------
     */
    @Override
    public void showLoading() {
        statusHandler.loading();
    }

    @Override
    public void showError() {
        //迁移到listener中统一埋点
        statusHandler.error();
    }

    @Override
    public void showEmpty() {
        statusHandler.empty();
    }

    @Override
    public void showContent() {
        statusHandler.showContent();
    }




}

